package com.bf.zk.user;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import com.bf.tool.DoCue;
import com.bf.zk.constants.Constants;
import com.bf.zk.table.CheckHeaderCellRenderer;
import com.bf.zk.table.CheckTableModle;
import com.bf.zk.table.UserMouseAdapter;
import com.bf.zk.table.UserTable;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;

public class SuperUserManage extends JFrame implements ActionListener,MouseListener {
	private static final long serialVersionUID = 1L;
	private JFrame SuperUserManagerWin;
	private JButton superUserManageDel;
	private JFrame parent;
	private JPanel contentPane;
	private JTable table;
	private Vector<String> headerNames;
	
	private DoCue dCue;
	private ArrayList<User> userdata=null;
	public SuperUserManage(JFrame parent, boolean modal) throws Exception {
		this.parent = parent;
		// 超级用户管理superUserManage
		JFrame.setDefaultLookAndFeelDecorated(true);
		JDialog.setDefaultLookAndFeelDecorated(true);
		SuperUserManagerWin = new JFrame("用户管理");
		SuperUserManagerWin.setSize(800, 600);
		SuperUserManagerWin.setDefaultCloseOperation(3);
		SuperUserManagerWin.setResizable(false);
		// 居中显示
		SuperUserManagerWin.setLayout(null);
		SuperUserManagerWin.setLocationRelativeTo(parent);
		SuperUserManagerWin.setIconImage(Toolkit.getDefaultToolkit().createImage("./pic/Log.jpg"));
		
		GetUserData();
		SuperUserManagerWin.getContentPane().setBackground(Constants.mycColor);
		// 用户列表
		userTable();
		RefreshUserList();
		// 增加
		JButton superUserManageAdd = new JButton("增加用户");
		superUserManageAdd.setActionCommand("superUserManageAdd");
		superUserManageAdd.setBounds(20, 485, 170, 60);
		superUserManageAdd.setFont(new Font("微软雅黑", Font.BOLD, 30));
		// 修改
		JButton superUserManageModify = new JButton("修改用户");
		superUserManageModify.setActionCommand("superUserManageModify");
		superUserManageModify.setBounds(210, 485, 170, 60);
		superUserManageModify.setFont(new Font("微软雅黑", Font.BOLD, 30));
		// 删除
		superUserManageDel = new JButton("删除用户");
		superUserManageDel.setActionCommand("superUserManageDel");
		superUserManageDel.setBounds(400, 485, 170, 60);
		superUserManageDel.setFont(new Font("微软雅黑", Font.BOLD, 30));
		// 返回
		JButton superUserManageBack = new JButton("返回");
		superUserManageBack.setActionCommand("superUserManageBack");
		superUserManageBack.setBounds(590, 485, 170, 60);
		superUserManageBack.setFont(new Font("微软雅黑", Font.BOLD, 30));

		SuperUserManagerWin.add(contentPane);
		SuperUserManagerWin.add(superUserManageAdd);
		SuperUserManagerWin.add(superUserManageModify);
		SuperUserManagerWin.add(superUserManageDel);
		SuperUserManagerWin.add(superUserManageBack);
		superUserManageAdd.addActionListener(this);
		superUserManageModify.addActionListener(this);
		superUserManageDel.addActionListener(this);
		superUserManageBack.addActionListener(this);
		SuperUserManagerWin.addMouseListener(this);
		table.getTableHeader().addMouseListener(this);
		SuperUserManagerWin.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// 增加用户
		if (e.getActionCommand().equals("superUserManageAdd")) {
			new UserAdd(SuperUserManagerWin, rootPaneCheckingEnabled);
			if (Constants.userOrNot&&!Constants.userOrNotCan) {
				userdata.add(Constants.addUser);
				RefreshUserList();
				dCue=new DoCue();//倒计时提示
				dCue.DoCue(SuperUserManagerWin,"添加成功!", 3);
			} else if(Constants.userOrNotCan){
				dCue=new DoCue();//倒计时提示
				dCue.DoCue(SuperUserManagerWin,"放弃操作!", 3);
			}else if (!Constants.userOrNot&&!Constants.userOrNotCan) {
				dCue=new DoCue();//倒计时提示
				dCue.DoCue(SuperUserManagerWin,"放弃操作!", 3);
			}else if (!Constants.userOrNot&&Constants.userOrNotCan) {
				dCue=new DoCue();//倒计时提示
				dCue.DoCue(SuperUserManagerWin,"添加失败!", 3);
			}
			Constants.userOrNot=false;
			Constants.userOrNotCan=false;
		}

		// 修改用户
		if (e.getActionCommand().equals("superUserManageModify")) {
			int count = 0;
			for (int rowindex = 0; rowindex < table.getRowCount(); rowindex++) {
				if ((boolean) table.getValueAt(rowindex, 0)) {
					count++;
					Constants.Modify0 = table.getValueAt(rowindex, 1).toString().trim();//id
					Constants.Modify1 = table.getValueAt(rowindex, 2).toString().trim();//name
					Constants.Modify2 = table.getValueAt(rowindex, 3).toString().trim();//pwd
					//System.out.println(Constants.Modify1 );
				}
			}
			if (count == 1) {
				new UserModify(SuperUserManagerWin, rootPaneCheckingEnabled);
				if (Constants.userOrNot&&!Constants.userOrNotCan) {
					String oleNameString;
					for (int i = 0; i < userdata.size(); i++) {
						oleNameString=userdata.get(i).getUserName();
						if(Constants.Modify1.equals(oleNameString)){
							
								userdata.get(i).setUserName(Constants.addUser.getUserName());
							
							userdata.get(i).setUserPwd(Constants.addUser.getUserPwd());
							break;
						}
					}
					//System.err.println(Constants.addUser.getUserName());
					RefreshUserList();
					
					Constants.Modify0 = "";
					Constants.Modify1 = "";
					Constants.Modify2 = "";
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(SuperUserManagerWin,"修改成功!", 3);
				} else if(Constants.userOrNotCan){
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(SuperUserManagerWin,"放弃操作!", 3);
				}else if(!Constants.userOrNot&&!Constants.userOrNotCan){
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(SuperUserManagerWin,"放弃操作!", 3);
				}else if(!Constants.userOrNot&&Constants.userOrNotCan){
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(SuperUserManagerWin,"修改失败!", 3);
				}
				Constants.userOrNot=false;
				Constants.userOrNotCan=false;
			} else {
				JOptionPane.showMessageDialog(SuperUserManagerWin, "选择一个操作目标!", "警告",JOptionPane.WARNING_MESSAGE);
			}
		}

		// 删除用户
		if (e.getActionCommand().equals("superUserManageDel")) {
			boolean flag = false;
			int addDelCount=0;
			for (int rowindex = 0; rowindex < table.getRowCount(); rowindex++) {
				if (((boolean) table.getValueAt(rowindex, 0))&&(!(((String) table.getValueAt(rowindex, 2)).equals("admin")))) {
					flag = true;
					addDelCount++;
					Constants.delList.add((String) table.getValueAt(rowindex, 2));
				}
			}
			if (flag) {
				int delCount=0;
				int cont = JOptionPane.showConfirmDialog(SuperUserManagerWin, "是否删除，数据将无法恢复?",	"提示", JOptionPane.OK_OPTION);
				if (cont == JOptionPane.OK_OPTION) {
					try {
						String fileName = "./sqlite/znzk.db";
						Class.forName("org.sqlite.JDBC");
						Connection conn = DriverManager.getConnection("jdbc:sqlite:" + fileName);
						Statement stmt = conn.createStatement();
						for (int rowindex = 0; rowindex < table.getRowCount(); rowindex++) {
							if ((boolean) table.getValueAt(rowindex, 0)) {
								boolean rs = stmt.execute("DELETE FROM znzk_user where username='"	+ (String) table.getValueAt(rowindex, 2) + "'");
								delCount++;
								for (int i = 0; i < userdata.size(); i++) {
									if((userdata.get(i).getUserName().trim()).equals((String) table.getValueAt(rowindex, 2))){
										userdata.remove(i);
										break;
									}
								}
							}
						}
						conn.close();
					} catch (Exception e2) {
					}
					if (addDelCount==delCount) {
						
						RefreshUserList();
						dCue=new DoCue();//倒计时提示
						dCue.DoCue(SuperUserManagerWin,"删除成功!", 3);
					}else {
						dCue=new DoCue();//倒计时提示
						dCue.DoCue(SuperUserManagerWin,"删除失败!", 3);
					}
				}else if(cont == JOptionPane.NO_OPTION){
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(SuperUserManagerWin,"放弃操作!", 3);
					RefreshUserList();
				}else if(cont == JOptionPane.CANCEL_OPTION){
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(SuperUserManagerWin,"放弃操作!", 3);
					RefreshUserList();
				}else {
					RefreshUserList();
				}
				
			} else {
				JOptionPane.showMessageDialog(SuperUserManagerWin, "选择一个操作目标!", "警告",JOptionPane.WARNING_MESSAGE);
			}
		}

		// 返回
		if (e.getActionCommand().equals("superUserManageBack")) {
			parent.setVisible(true);
			SuperUserManagerWin.setVisible(false);
		}
	}

	public final void RefreshUserList() {
		initUserTable();
		table.getColumnModel().getColumn(0).setMinWidth(82);
		table.getColumnModel().getColumn(0).setMaxWidth(82);
		table.getColumnModel().getColumn(1).setMinWidth(0);
		table.getColumnModel().getColumn(1).setMaxWidth(0);
		table.getColumnModel().getColumn(2).setMinWidth(250);
		table.getColumnModel().getColumn(2).setMaxWidth(250);
		table.getColumnModel().getColumn(3).setMinWidth(250);
		table.getColumnModel().getColumn(3).setMaxWidth(250);
	}

	private void userTable() {
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		table = new UserTable();
		table.addMouseListener(new UserMouseAdapter() {
	     	   @SuppressWarnings("static-access")
			public void mouseSingleClicked(final MouseEvent e){
	     		  if (e.getButton() == e.BUTTON1) {
	     			  int rowI  = table.rowAtPoint(e.getPoint());// 得到table的行号
	     			  int col=table.columnAtPoint(e.getPoint());
	     			  if (0<col) {
	     				  if ((boolean) table.getValueAt(rowI, 0)) {
	     					  table.setValueAt(false, rowI, 0);
	     				  } else {
	     					  table.setValueAt(true, rowI, 0);
	     				  }
	     			  }
	  			}
	     	  }
	     	   @SuppressWarnings("unused")
			public void mouseDoubleClicked(MouseEvent e){
		     	      int rowI  = table.rowAtPoint(e.getPoint());// 得到table的行号
		     	     int col=table.columnAtPoint(e.getPoint());
		     	     if (rowI > -1){
		     	         //System.out.println("双击鼠标 "+(table.getModel()).getValueAt(rowI, 1));
		     	     }
		     	    
	     	    }
	     	  });
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
		tcr.setHorizontalAlignment(JLabel.CENTER);
		table.getTableHeader().setReorderingAllowed(false); 
		table.setDefaultRenderer(Object.class, tcr);
		table.setBorder(null);
		
		//table.setShowVerticalLines(false);
		table.setRowHeight(40);// 设置行高
		table.setFont(new Font("", Font.PLAIN, 30));
		JScrollPane scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		contentPane.add(scrollPane);
		contentPane.setBounds(70, 5, 600, 447);
		headerNames = new Vector<String>();
		headerNames.add("全选");
		headerNames.add("ID");
		headerNames.add(" 用户名 ");
		headerNames.add(" 密码  ");
		//headerNames.add("用户类型");
		// pack();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void initUserTable() {
		int rowCount = ((DefaultTableModel) table.getModel()).getRowCount();
		// 删除表里之前内容
		for (int i = rowCount - 1; i >= 0; i--) {
			((DefaultTableModel) table.getModel()).removeRow(i);
		}
		Vector<Vector<Comparable>> data = this.getData();
		CheckTableModle tableModel = new CheckTableModle(data, headerNames);
		table.setModel(tableModel);
		table.getTableHeader().setDefaultRenderer(new CheckHeaderCellRenderer(table));
	}

	// 获得数据
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Vector getData() {
		Vector data = new Vector();
		for (int i = 0; i < userdata.size(); i++) {
			Vector rowVector1 = new Vector();
			//userdata.get(i);
			rowVector1.add(userdata.get(i).isChooseUser());
			rowVector1.add(userdata.get(i).getUserId());
			rowVector1.add(userdata.get(i).getUserName());
			rowVector1.add(userdata.get(i).getUserPwd());
			//rowVector1.add(userdata.get(i).getUserType());
			data.add(rowVector1);
		}
		
		return data;
	}

	private void GetUserData() throws Exception{
		userdata=new ArrayList<User>();
		String fileName = "./sqlite/znzk.db";
		Class.forName("org.sqlite.JDBC");
		Connection conn = DriverManager.getConnection("jdbc:sqlite:" + fileName);
		Statement stmt = conn.createStatement();
		java.sql.ResultSet rs = stmt.executeQuery("SELECT * FROM znzk_user");
		while (rs.next()) {
			User rowUser = new User();
			rowUser.setChooseUser(false);
			rowUser.setUserId(rs.getString("userid"));
			rowUser.setUserName(rs.getString("username"));
			rowUser.setUserPwd(rs.getString("password"));
			//rowUser.setUserType(rs.getString("user_type"));
			userdata.add(rowUser);
		}
		conn.close();
		
	}
	//添加响应排序
	@SuppressWarnings("static-access")
	public void mouseClicked(MouseEvent e) {
		if ((e.getButton() == e.BUTTON1)) {
			
		}
	}

	public void mousePressed(MouseEvent e) {}
	public void mouseReleased(MouseEvent e) {}
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	
}
